import cv2
from TOOL import fenkuai
import numpy as np

t = 5


def average_gray(img):  # 计算图像的灰度平均值

    # img = cv.imread(img, 0)
    height, width = img.shape[:2]

    size = img.size

    average = 0
    for i in range(height):
        for j in range(width):
            average += img[i][j] / size

    # print("平均值" + str(average))
    return average


def average_recover(img, average_old, verage_new):  # 通过改变后的平均值进行图片还原,参数分别是原始图片，原始图片平均值，改变后图片平均值
    # img = cv.imread(img, 0)

    height = img.shape[0]
    width = img.shape[1]
    size = img.size
    img_new = np.zeros((height, width))
    # print(height, width)
    for i in range(height):
        for j in range(width):
            img_new[i][j] = (verage_new * img[i][j]) / average_old
            # print("img_new[" + str(i) + "]" + "[" + str(j) + "]:   " + str(img_new[i][j]))
    # cv2.imwrite("result.jpg", img_new)
    return img_new


def bit_insert(image_block_one, bit):  # 处理每位比特对应分块图像的函数，根据比特01区别对均值进行处理

    double_block = fenkuai.qiege1(2, 1, image_block_one, 2)  # 将当前块的图像分割为两部分
    # print(double_block[0, 0, :].shape)
    dA = cv2.cvtColor(double_block[0, 0, :], cv2.COLOR_RGB2GRAY)  # 分别赋予dA,dB两个变量对应图像，灰度化
    dB = cv2.cvtColor(double_block[1, 0, :], cv2.COLOR_RGB2GRAY)

    da1 = 0  # 代表修改后各方块的平均值
    db1 = 0
    bit_end = 0
    da = average_gray(dA)
    db = average_gray(dB)
    print(bit)
    if bit == 1:
        if da - db < 0:
            da1 = da + t
            db1 = db - t
            if da1 - db1 < 0:
                print("t取值过小")
                bit_end = 0
        else:
            da1 = da
            db1 = db
            bit_end = 1
    else:  # bit=0的情况
        if da - db >= 0:
            da1 = da - t
            db1 = db + t
            if da1 - db1 >= 0:
                print("t取值过小")
                bit_end = 1
        else:
            da1 = da
            db1 = db
            bit_end = 0
    # print("修改后的平均值dA，dB为" + str(da1) + "   " + str(db1))
    return da, db, da1, db1, dA, dB, bit_end


def bit_read(image_block_one):  # 处理每位比特对应分块图像的函数，根据比特01区别对均值进行处理

    double_block = fenkuai.qiege1(2, 1, image_block_one, 5)  # 将当前块的图像分割为两部分
    # print(double_block[0, 0, :].shape)
    dA = cv2.cvtColor(double_block[0, 0, :], cv2.COLOR_RGB2GRAY)  # 分别赋予dA,dB两个变量对应图像，灰度化
    dB = cv2.cvtColor(double_block[1, 0, :], cv2.COLOR_RGB2GRAY)

    da = average_gray(dA)
    db = average_gray(dB)

    if da - db > 0:
        bit = 1
    else:  # bit=0的情况
        bit = 0

    # print("修改后的平均值dA，dB为" + str(bit))
    return bit
